package com.example;

import java.util.Random;

/**
 * ThreadLocal是Java中的一个类，它提供了线程局部变量的功能。每个ThreadLocal实例都可以在每个线程中维护一个独立的变量副本，
 * 该变量对其他线程是不可见的。换句话说，每个线程可以独立地读取和修改自己的ThreadLocal变量，而不会影响其他线程的副本。
 * 使用ThreadLocal的基本流程如下：
 * 创建一个ThreadLocal实例：ThreadLocal<T> threadLocal = new ThreadLocal<>();
 * 设置当前线程的变量值：threadLocal.set(value);
 * 获取当前线程的变量值：T value = threadLocal.get();
 * 清除当前线程的变量值：threadLocal.remove();
 * @author xiaohongfei
 * @createTime 2023/10/13 08:52
**/
public class ThreadLocalTest {

        private static ThreadLocal<Integer> threadLocal = new ThreadLocal<>();
//    private static ThreadLocal<Integer> threadLocal = new InheritableThreadLocal<>();
        public static void main(String[] args) {
            // Create and start multiple threads
            Thread thread1 = new Thread(new MyRunnable());
            Thread thread2 = new Thread(new MyRunnable());
            thread1.start();
            thread2.start();

            // Wait for threads to complete
            try {
                thread1.join();
                thread2.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            // Get the final values from each thread
            Integer value1 = threadLocal.get();
            Integer value2 = threadLocal.get();

            System.out.println("Final value from Thread 1: " + value1);
            System.out.println("Final value from Thread 2: " + value2);
        }

        static class MyRunnable implements Runnable {
            @Override
            public void run() {
                // Generate a random number and store it in the ThreadLocal variable
                int randomNumber = new Random().nextInt(100);
                threadLocal.set(randomNumber);

                // Perform some operations using the ThreadLocal variable
                int result = randomNumber * 2;

                // Print the intermediate value
                System.out.println("Intermediate value in Thread: " + result);

                // Clear the ThreadLocal variable
//                threadLocal.remove();
            }
        }

}
